﻿using siqi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace siqi.Logic
{
    class Desk : Interfaces.IDesk
    {
        public Desk(string id, string name)
        {
            ID = id;
            Name = name;
            Seats = new List<Interfaces.ISeat>();
            Visitors = new List<IUserAgent>();
        }

        private Queue<MessageToken> mQueue = new Queue<MessageToken>();

        public string ID
        {
            get;
            set;
        }
        public IList<IUserAgent> Visitors { get; private set; }
    
    
        public string Name
        {
            get;
            set;
        }

        public IList<Interfaces.ISeat> Seats
        {
            get;
            private set;
        }

        public void Add(Interfaces.ISeat seat)
        {
            Seats.Add(seat);
        }

        public Interfaces.IRoom Room
        {
            get;
            set;
        }

        public string In(Interfaces.IUserAgent user, int seatIndex)
        {
            Protocol.Result result = new Protocol.Result();
            result.Success = true;

            if (user.Desk != null)
                user.Desk.Exit(user);
            for (int i = 0; i < Seats.Count; i++)
            {
                Interfaces.ISeat seat = Seats[i];
                if (seat.Index == seatIndex)
                {
                    if (seat.User == null || seat.User == user)
                    {
                        seat.User = user;
                        user.Desk = this;
                        
                        
                    }
                    else
                    {
                        result.Success = false;
                        return "位置已经被占用!";
                    }
                }
            }
            if (!Visitors.Contains(user))
                Visitors.Add(user);
            return null;

        }

        public void Exit(Interfaces.IUserAgent user)
        {
            if (user.Desk == this)
            {
                if(user.Seat !=null)
                    user.Seat.User = null;
                user.Seat = null;
                user.Desk = null;
                Visitors.Remove(user);

            }
        }

        public void AddMessage(Protocol.IMessage message, Interfaces.IUserAgent user)
        {

        }
        protected virtual void OnExecute(MessageToken token, ISiqiServer server)
        {
            //添加处理逻辑
        }
        public void Execute(ISiqiServer server)
        {

        }
    }
}
